package proxy;


import net.sf.cglib.proxy.*;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class CglibProxyTest {
    public static void main(String[] args) {
//创建一个实例对象，这个对象是被代理的对象
        Student zhangsan = new Student("张三");
        // 创建动态代理增强类
        Enhancer enhancer = new Enhancer();
        // 设置类加载器
        enhancer.setClassLoader(CglibProxyTest.class.getClassLoader());
        // 设置被代理类
        enhancer.setSuperclass(Student.class);
        enhancer.setCallbackFilter(new CallbackFilter() {
            @Override
            public int accept(Method method) {
                return 0;
            }
        });
        // 设置方法拦截器
        enhancer.setCallbacks(new Callback[]{new StuMethodInterceptor(),new StuMethodInterceptor()});
        // 创建代理类
        Person personProxy = (Person) enhancer.create(new Class[]{String.class}, new Object[]{"张三"});
        //Person personProxy = (Person) enhancer.create(zhangsan);

        //代理执行上交班费的方法
        personProxy.giveMoney();
    }
}


class StuMethodInterceptor implements MethodInterceptor {


    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("代理执行" + method.getName() + "方法");

        //代理过程中插入监测方法,计算该方法耗时
        MonitorUtil.start();
        Object result = methodProxy.invokeSuper(o, args);
        MonitorUtil.finish(method.getName());
        return result;
    }
}